<?php


namespace Catmes\LayAdmin\Components\LayJs;


use Catmes\LayAdmin\Components\Template;
use Catmes\LayAdmin\helpers\ArrayHelper;

class JsAjax
{
    const JS_RESPONSE = "layer.alert(data.msg,{title: '操作结果'});";
    /* @var string $url URL链接必须自己包含引号。如： $url = "\"/admin/videos/delete\""; */
    protected $url = '';
    protected $type = 'POST';
    protected $data = [];
    protected $jsVars = [];
    protected $success = self::JS_RESPONSE;
    public function __construct($url, array $data, $type='POST'){
        if(strpos($url, "\"")===false && strpos($url, "'")===false){
            // url 字符串， 不包含 单引号'或双引号"， 则自动在字符串两边加双引号"。
            $url = "\"" . $url . "\"";
        }
        $this->url = $url;
        $this->data = $data;
        $this->type = strtoupper($type);
    }
    public function setJsVars($vars=[]):self{
        $this->jsVars = $vars;
        return $this;
    }
    public function setSuccess($success=self::JS_RESPONSE):self{
        $this->success = $success;
        return $this;
    }
    protected function getJsStr():string{
        // URL链接必须自己包含引号。如： $url = "\"/admin/videos/delete\"";
        $template = Template::getInstance();
        $tokenField = $template->getCsrfTokenField();
        $csrfToken = $template->getCsrfToken();
        $this->data[$tokenField] = $csrfToken;
        $data = ArrayHelper::toJsonObject($this->data, $this->jsVars);
        return <<<AJAXTPL
                    $.ajax({
                        type: '{$this->type}',
                        url: {$this->url},
                        data: {$data},
                        success: function (data, status) {
                            {$this->success}
                        }
                        // dataType: json
                    });
AJAXTPL;
    }

    public function render():string{
        return $this->getJsStr();
    }

    public function __toString(){
        return $this->render();
    }


}
